; Simple display

; Some NES ports
export port ppuControl = $2000
export port ppuMask = $2001
export port ppuStatus = $2002
export port ppuAddress = $2006
export port ppuData = $2007
export port apuDmcFrequencey = $4010
export port oamDma = $4014
export port apuFrameCounter = $4017

export sub main
	; Set up registers
	apuFrameCounter = $40
	apuDmcFrequencey = 0
	ppuControl = 0
	ppuMask = 0
	
	; Assembly block to clear RAM and wait for PPU warmup
	asm
		bit	ppuStatus
		ppuWait1:
			bit	ppuStatus
			bpl	ppuWait1
		ldx #$00
		loop:
			lda #$ff	; Page $02 needs to be cleared to $FF to force OAM data
			sta	$0200,x	; off-screen. Change this page if you don't use $02 for
			lda #$00	; the OAM DMA buffer.
			sta $0000,x
			sta $0100,x
			sta $0300,x
			sta $0400,x
			sta $0500,x
			sta $0600,x
			sta $0700,x
			dex
			bne	loop
		ppuWait2:
			bit	ppuStatus
			bpl	ppuWait2
	end asm
	
	; Load palette data
	byte idx
	idx = 0
	ppuAddress = $3f
	ppuAddress = $00
	while idx < 40
		ppuData = idx
		idx = idx + 1
		if idx == 12
			idx = 16
		else if idx == 28
			idx = 32
		end if
	end while
	
	; Upload a test pattern
	ppuAddress = $00
	ppuAddress = $00
	idx = 0
	loop
		ppuData = %10011001
		ppuData = %00100100
		ppuData = %00100100
		ppuData = %01000010
		ppuData = %01000010
		ppuData = %00100100
		ppuData = %00100100
		ppuData = %10011001
		idx = idx + 1
	end loop when idx == 2
	
	; Clear the nametable
	word ntWriteCount
	ntWriteCount = 0
	ppuAddress = $20
	ppuAddress = $00
	while ntWriteCount < $1000
		ppuData = 0
		ntWriteCount = ntWriteCount + 1
	end while
	
	; Enable rendering
	ppuControl = %1000000
	ppuMask = %00011110
	
	; Program loop
	loop
	end loop
end sub

export sub frame
	; OAM DMA, takes about 513 cycles
	oamDma = $02
end sub

export sub interrupt
end sub
